<template>
    <!-- 采购管理 -->
    <div class="purchase-container">
        <!-- 顶部导航栏 -->
        <div class="purchase-nav">
            <!-- 单选  切换操作/显示 -->
            <el-radio-group class="w-full" v-model="tools">
                <el-radio value="options" size="large">操作栏(快捷键:ALT+Q)</el-radio>
                <el-radio value="show" size="large">展示栏(快捷键:ALT+W)</el-radio>
            </el-radio-group>

            <!-- 操作栏 -->
            <div v-if="tools === 'options'" class="purchase-options w-full">
                <!-- 常驻 -->
                <!-- 搜索栏 -->
                <el-input
                    class="mr-2"
                    v-model="searchPurchaseValue"
                    placeholder="请输入采购关键字"
                    @keydown.enter="getPurchaseListEvent"
                    clearable
                    @clear="getPurchaseListEvent"
                    style="width: 250px"
                />
                <el-button @click="getPurchaseListEvent" :icon="Search">搜索</el-button>
                <el-button :icon="Refresh" text @click="getPurchaseListEvent">刷新</el-button>

                <!-- 正面 -->
                <!-- 刷新 -->
                <!-- 回收站 -->
                <el-button v-if="available" type="info" :icon="SwitchHorizontal" text @click="enterRecycleEvent">回收站</el-button>
                <!-- 删除 -->
                <el-button v-if="available" type="warning" :icon="Delete24Regular" text @click="deletePurchaseEvent">删除</el-button>
                <!-- 隐患评估 -->
                <el-button v-if="available" :icon="TreeFallRisk" text @click="getPurchaseRiskAssessmentEvent">隐患评估</el-button>
                <!-- 打印 -->
                <el-dropdown v-if="available" trigger="click">
                    <el-button class="w-full ml-2 mr-2" plain text :icon="ArrowDown">打印</el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <!-- 打印生产单 -->
                            <el-dropdown-item>
                                <el-button :icon="Printer" text @click="printProductionEvent">打印生产单</el-button>
                            </el-dropdown-item>
                            <!-- 打印标签 -->
                            <el-dropdown-item>
                                <el-button :icon="Label" text @click="printLabelEvent">打印采购标签</el-button>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <!-- 采购操作 -->
                <el-dropdown v-if="available" trigger="click">
                    <el-button class="w-full" plain text :icon="ArrowDown">操作</el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <!-- 转库存 -->
                            <el-dropdown-item>
                                <el-button :icon="Switch2" text @click="transferStockEvent">转库存纸</el-button>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>

                <!-- 反面 -->
                <!-- 恢复按钮 -->
                <el-button v-if="!available" type="info" :icon="SwitchHorizontal" text @click="returnPurchaseEvent">操作栏</el-button>
                <!-- 切换按钮 -->
                <el-button v-if="!available" type="success" :icon="MagicWand" text @click="recoverPurchaseEvent">恢复</el-button>
                <!-- 打印生产单/移除 -->
                <el-button v-if="!available" type="danger" :icon="DeleteOff24Regular" text @click="removePurchaseEvent">移除</el-button>
            </div>

            <!-- 展示栏 -->
            <div v-if="tools === 'show'" class="purchase-show w-full">
                <el-checkbox-group v-model="usePurchase.able" @change="checkBoxChangeEvent">
                    <el-checkbox
                        v-for="(item, index) in checkBoxOptions"
                        :key="index"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                    />
                </el-checkbox-group>
            </div>
        </div>

        <!-- 采购表格 -->
        <div class="purchase-table">
            <el-auto-resizer>
                <template #default="{ height, width }">
                    <FTableV2
                        v-model="selected"
                        :width="width"
                        :height="height"
                        :row-height="rowHeight"
                        :data="data"
                        :other-column="otherColumn"
                        :disable="usePurchase.disable"
                    ></FTableV2>
                </template>
            </el-auto-resizer>
        </div>

        <!-- 分页 -->
        <div class="purchase-pagination">
            <el-pagination
                v-model:current-page="page"
                v-model:page-size="pageSize"
                @change="handleSizeChange"
                :total="total"
                :page-sizes="[10, 20, 30, 40, 50, 100]"
                layout="prev, pager, next, sizes, jumper, ->, total"
                background
            />
        </div>
    </div>

    <!-- 打印标签 -->
    <printPurchaseLabel
        v-model:print-purchase-label-visible="printPurchaseLabelVisible"
        v-model:print-purchase-label-data="printPurchaseLabelData"
    ></printPurchaseLabel>
    <!-- 打印生产单 -->
    <printProduction v-model:print-visible="printVisible" :print-btn-symbol="true" v-model:print-data="printData"></printProduction>

    <!-- 上传单据信息 -->
    <el-dialog v-model="uploadprocurementControlInfoVisible" :close-on-click-modal="false" :show-close="false" draggable>
        <!-- 自定义标题 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">上传单据信息</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <div class="flex flex-wrap items-center justify-between">
            <div class="w-full mb-2">
                <label for="procurementControlInfo-arrivalQuantity">到货数量：</label>
                <el-input-number v-model="procurementControlInfo.arrivalQuantity" placeholder="请输入到货数量"></el-input-number>
            </div>
            <div class="w-full mb-2">
                <label for="procurementControlInfo-arrivalAmount">到货金额：</label>
                <el-input-number v-model="procurementControlInfo.arrivalAmount" placeholder="请输入到货金额"></el-input-number>
            </div>
            <el-button type="primary" @click="uploadProcurementControlInfoEvent">确认录入</el-button>
        </div>
    </el-dialog>

    <!-- 上传采购凭证 -->
    <el-dialog
        v-model="uploadProcurementControlReceiptsVisible"
        :close-on-click-modal="false"
        :show-close="false"
        @open="addEventListenerEvent"
        @close="removeEventListenerEvent"
    >
        <!-- 自定义标题 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">上传采购凭证 -- 支持检测【CTRL+V】键</h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!-- 自定义内容 -->
        <div>
            <img v-if="imageSrc" :src="imageSrc" alt="粘贴板图片" />
            <el-button v-if="imageSrc" plain :icon="CloudUpload" @click="uploadProcurementControlReceiptsEvent">上传</el-button>
        </div>
    </el-dialog>
</template>

<script setup lang="tsx">
import { Search, Printer, SwitchHorizontal, CloudUpload, Switch2 } from '@vicons/tabler';
import { MagicWand, TreeFallRisk, Label } from '@vicons/carbon';
import { Delete24Regular, DeleteOff24Regular } from '@vicons/fluent';
import { CheckboxValueType, Column, ElInput, ElCheckbox, ElDatePicker, ElText, ElButton, ElImage } from 'element-plus';
import { Refresh, CircleCloseFilled, ArrowDown } from '@element-plus/icons-vue';
import { deletePurchase, getPurchaseList, recoverPurchase, removePurchase, transferStock, updatePurchase } from '@api/purchase';
import { uploadProcurementControlInfo, deleteProcurementControlReceipts, skipProcurementControlReceipts } from '@api/purchase';
import { getPurchaseRiskAssessment } from '@/api/purchase';
import { usePurchaseStore } from '@/store/modules/purchase';
import { FunctionalComponent } from 'vue';
import { checkPermi } from '@utils/permission';
import { HttpUrl } from '@/api/httpUrl';
import { formatTimeZone } from '@utils/calculate';

onMounted(() => {
    // 计算列高 -- 根据屏幕高度动态计算
    const tableRef = document.getElementsByClassName('purchase-table')[0];
    pageSize.value = Math.floor((Number(tableRef.clientHeight) - rowHeight.value) / rowHeight.value);

    // 获取采购
    getPurchaseListEvent();
    // 第一次计算pageSize不用更新，后续更新
    pageSizeSymbol.value = true;

    // 获取采购安全隐患评估
    getPurchaseRiskAssessmentEvent();

    // 检测alt+q/alt+w切换
    addEventListener('keydown', (e) => {
        if (e.altKey && e.key.toLocaleLowerCase() === 'q') {
            // 切换到操作栏
            tools.value = 'options';
        } else if (e.altKey && e.key.toLocaleLowerCase() === 'w') {
            // 切换到展示栏
            tools.value = 'show';
        }
    });
    // 取消监听
    onUnmounted(() => {
        removeEventListener('keydown', (e) => {
            if (e.altKey && e.key.toLocaleLowerCase() === 'q') {
                // 切换到操作栏
                tools.value = 'options';
            } else if (e.altKey && e.key.toLocaleLowerCase() === 'w') {
                // 切换到展示栏
                tools.value = 'show';
            }
        });
    });
});

/* ******************************通用属性/方法****************************** */
// 采购store
const usePurchase = usePurchaseStore();

// 操作栏激活切换
const available = ref(true);
// 选择的行
const selected = reactive<string[]>([]);
// 行高
const rowHeight = ref(62);
// 当前分页页码
const page = ref(1);
// 每页显示数量
const pageSize = ref(10);
// 第一次自适应不需要更新列表
const pageSizeSymbol = ref(false);
// 总数
const total = ref(0);

// 当前服务器主机名和端口
const httpUrl = import.meta.env.VITE_APP_SERVER_URL;
// 获取采购列表
const getPurchaseListEvent = async () => {
    // 获取采购列表
    getPurchaseList(available.value, searchPurchaseValue.value, page.value, pageSize.value).then((res) => {
        // 清空通用属性
        data.length = 0;
        selected.length = 0;
        // 取出数据
        res.data.forEach((item, index) => {
            item.order = index + 1;
            item.checked = false;
            item.editing = false;
            data.push(item);
        });
        // 设置总数
        total.value = res.count;
    });
};

// 采购安全隐患评估
const getPurchaseRiskAssessmentEvent = () => {
    // 超过5天的未到货的采购单 || 采购单没有采购凭据的
    getPurchaseRiskAssessment().then((res) => {
        // 加工数据
        // @ts-ignore
        const riskAssessment: RiskAssessment[] = res.data.map((item) => {
            let riskFactors = '';
            // 没有采购凭据
            if (item.procurementControlReceipts.length === 0) {
                riskFactors += '无采购凭据;';
            }
            // 超过5天的未到货
            if (item.arrivalDate == null) {
                // 下单的时间
                // @ts-ignore
                const date1 = new Date(item.createdAt);
                // 当前时间
                const date2 = new Date();
                // 相差的天数
                const diff = date2.getTime() - date1.getTime();
                // 天数
                const days = Math.floor(diff / (24 * 3600 * 1000));
                if (days >= 5) {
                    riskFactors += '超期5天未到货;';
                }
            }
            return {
                purchaseId: item._id,
                createdAt: item.createdAt,
                supplierAbbreviation: item.supplierAbbreviation,
                productName: item.productName,
                purchaseSize: item.tissueSize == '' ? item.corrugatedSize : item.tissueSize,
                purchaseNumber: item.purchaseNumber,
                riskFactors: riskFactors,
            };
        });
        usePurchase.addPurchaseRiskAssessment(riskAssessment, res.total as number);
    });
};

/* ******************************单选工具属性/方法****************************** */
// 单选工具
const tools = ref<'options' | 'show'>('options');

/* ******************************Tablev表单属性/方法****************************** */

// 表格数据
const data = reactive<AjaxResponse['purchaseList']>([]);
// 禁用列 usePurchase.disable
// const disable = usePurchase.disable;

// input函数式组件
type InputCessProps = {
    value: string;
    type: string;
    // 在 Input 值改变时触发
    onInput?: (value: string) => void;
    // 当选择器的输入框获得焦点时触发
    onFocus?: () => void;
    // 当选择器的输入框失去焦点时触发
    onBlur?: () => void;
};
const InputCell: FunctionalComponent<InputCessProps> = ({ value, type, onFocus, onBlur, onInput }) => {
    return <ElInput modelValue={value} type={type} onFocus={onFocus} onBlur={onBlur} onInput={onInput} />;
};
// checkbox函数式组件
type CheckBoxCellProps = {
    value: boolean;
    intermediate?: boolean;
    disabled?: boolean;
    onChange?: (value: CheckboxValueType) => void;
};
const CheckBoxCell: FunctionalComponent<CheckBoxCellProps> = ({ value, intermediate = false, disabled = false, onChange }) => {
    return <ElCheckbox size={'large'} modelValue={value} indeterminate={intermediate} disabled={disabled} onChange={onChange} />;
};
// datepicker函数式组件
type DatePickerProps = {
    value: Date | '';
    onUpdate: (value: Date) => void;
};
const DatePickerCell: FunctionalComponent<DatePickerProps> = ({ value, onUpdate }) => {
    return <ElDatePicker modelValue={value} placeholder="选择到货日期" onUpdate:modelValue={onUpdate} />;
};
// 输入框的原始值
let inputOriginValue = '';
// 表格独有的column
const otherColumn = reactive<{ [key: string]: Column<any> }>({
    customerAbbreviation: {
        width: 90,
        key: 'customerAbbreviation',
        dataKey: 'customerAbbreviation',
        title: '客户',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    orderStatus: {
        width: 75,
        key: 'orderStatus',
        dataKey: 'orderStatus',
        title: '订单状态',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            if (rowData[column.dataKey!] == 'primary') {
                return (
                    <ElText type={'primary'} tag={'b'}>
                        正常
                    </ElText>
                );
            } else if (rowData[column.dataKey!] == 'warning') {
                return (
                    <ElText type={'warning'} tag={'b'}>
                        加急
                    </ElText>
                );
            } else {
                return (
                    <ElText type={'danger'} tag={'b'}>
                        特急
                    </ElText>
                );
            }
        },
    },
    orderNo: {
        width: 150,
        key: 'orderNo',
        dataKey: 'orderNo',
        title: '订单号',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    productName: {
        width: 180,
        key: 'productName',
        dataKey: 'productName',
        title: '产品名称',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    productSize: {
        width: 120,
        key: 'productSize',
        dataKey: 'productSize',
        title: '产品尺寸',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    supplierAbbreviation: {
        width: 75,
        key: 'supplierAbbreviation',
        dataKey: 'supplierAbbreviation',
        title: '供应商',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    tissueSize: {
        width: 110,
        key: 'tissueSize',
        dataKey: 'tissueSize',
        title: '面纸规格',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    corrugatedSize: {
        width: 110,
        key: 'corrugatedSize',
        dataKey: 'corrugatedSize',
        title: '瓦楞规格',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            //计算平方
            if (rowData[column.dataKey!] != '') {
                const width = Number(rowData[column.dataKey!].split('*')[0]);
                const height = Number(rowData[column.dataKey!].split('*')[1]);
                const area = width * height * 0.000001;
                return (
                    <div>
                        <div class={'text'}>{rowData[column.dataKey!]}</div>
                        <div>({area.toFixed(2)}m²)</div>
                    </div>
                );
            } else {
                return <div class={'text'}>{rowData[column.dataKey!]}</div>;
            }
        },
    },
    materialQuality: {
        width: 235,
        key: 'materialQuality',
        dataKey: 'materialQuality',
        title: '材质',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    crimping: {
        width: 135,
        key: 'crimping',
        dataKey: 'crimping',
        title: '压线',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    spell: {
        width: 50,
        key: 'spell',
        dataKey: 'spell',
        title: '拼数',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    orderNumber: {
        width: 90,
        key: 'orderNumber',
        dataKey: 'orderNumber',
        title: '订单数量',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    purchaseNumber: {
        width: 110,
        key: 'purchaseNumber',
        dataKey: 'purchaseNumber',
        title: '采购数量',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 输入框编辑模式
            const onEnterEditMode = () => {
                rowData.editing = true;
                inputOriginValue = rowData[column.dataKey!];
            };

            // 输入框内容改变时触发
            const onInput = (value: string) => {
                rowData[column.dataKey!] = value;
            };

            // 输入框退出编辑模式 -- 更新到服务器
            const onExitEditMode = () => {
                // 输入框退出编辑模式
                rowData.editing = false;
                // 对比新旧值
                if (rowData[column.dataKey!] !== inputOriginValue) {
                    // 更新到服务器
                    if (checkPermi(['purchase:update'])) {
                        updatePurchase(rowData._id, column.dataKey!, rowData[column.dataKey!]).then(() => {
                            ElMessage.success('更新成功');
                        });
                    } else {
                        ElMessage.error('没有权限');
                    }
                }
            };

            const width = Number(rowData['corrugatedSize'].split('*')[0]);
            const height = Number(rowData['corrugatedSize'].split('*')[1]);
            const area = width * height * 0.000001 * Number(rowData[column.dataKey!]) || 0;
            const show = rowData['corrugatedSize'] !== '' && rowData['tissueSize'] == '';

            return rowData.editing ? (
                <InputCell type={'text'} value={rowData[column.dataKey!]} onFocus={onEnterEditMode} onBlur={onExitEditMode} onInput={onInput} />
            ) : (
                <div
                    class={rowData[column.dataKey!] === '' ? 'table-v2-inline-editing-trigger-trim text' : 'table-v2-inline-editing-trigger text'}
                    onClick={onEnterEditMode}
                >
                    <div>{rowData[column.dataKey!]}</div>
                    <div style={show ? '' : 'display:none'}>({area.toFixed(2)}m²)</div>
                </div>
            );
        },
    },
    arrivalTo: {
        width: 80,
        key: 'arrivalTo',
        dataKey: 'arrivalTo',
        title: '送货地址',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 输入框编辑模式
            const onEnterEditMode = () => {
                rowData.editing = true;
                inputOriginValue = rowData[column.dataKey!];
            };

            // 输入框内容改变时触发
            const onInput = (value: string) => {
                rowData[column.dataKey!] = value;
            };

            // 输入框退出编辑模式 -- 更新到服务器
            const onExitEditMode = () => {
                // 输入框退出编辑模式
                rowData.editing = false;
                // 对比新旧值
                if (rowData[column.dataKey!] !== inputOriginValue) {
                    // 更新到服务器
                    if (checkPermi(['purchase:update'])) {
                        updatePurchase(rowData._id, column.dataKey!, rowData[column.dataKey!]).then(() => {
                            ElMessage.success('更新成功');
                        });
                    } else {
                        ElMessage.error('没有权限');
                    }
                }
            };
            return rowData.editing ? (
                <InputCell type={'text'} value={rowData[column.dataKey!]} onFocus={onEnterEditMode} onBlur={onExitEditMode} onInput={onInput} />
            ) : (
                <div
                    class={rowData[column.dataKey!] === '' ? 'table-v2-inline-editing-trigger-trim text' : 'table-v2-inline-editing-trigger text'}
                    onClick={onEnterEditMode}
                >
                    {rowData[column.dataKey!]}
                </div>
            );
        },
    },
    orderRemark: {
        width: 180,
        key: 'orderRemark',
        dataKey: 'orderRemark',
        title: '订单备注',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 输入框编辑模式
            const onEnterEditMode = () => {
                rowData.editing = true;
                inputOriginValue = rowData[column.dataKey!];
            };

            // 输入框内容改变时触发
            const onInput = (value: string) => {
                rowData[column.dataKey!] = value;
            };

            // 输入框退出编辑模式 -- 更新到服务器
            const onExitEditMode = () => {
                // 输入框退出编辑模式
                rowData.editing = false;
                // 对比新旧值
                if (rowData[column.dataKey!] !== inputOriginValue) {
                    // 更新到服务器
                    if (checkPermi(['purchase:update'])) {
                        updatePurchase(rowData._id, column.dataKey!, rowData[column.dataKey!]).then(() => {
                            ElMessage.success('更新成功');
                        });
                    } else {
                        ElMessage.error('没有权限');
                    }
                }
            };

            return rowData.editing ? (
                <InputCell type={'textarea'} value={rowData[column.dataKey!]} onFocus={onEnterEditMode} onBlur={onExitEditMode} onInput={onInput} />
            ) : (
                <div
                    class={rowData[column.dataKey!] === '' ? 'table-v2-inline-editing-trigger-trim text' : 'table-v2-inline-editing-trigger text'}
                    onClick={onEnterEditMode}
                >
                    {rowData[column.dataKey!]}
                </div>
            );
        },
    },
    purchaseNotes: {
        width: 186,
        key: 'purchaseNotes',
        dataKey: 'purchaseNotes',
        title: '采购备注',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 输入框编辑模式
            const onEnterEditMode = () => {
                rowData.editing = true;
                inputOriginValue = rowData[column.dataKey!];
            };

            // 输入框内容改变时触发
            const onInput = (value: string) => {
                rowData[column.dataKey!] = value;
            };

            // 输入框退出编辑模式 -- 更新到服务器
            const onExitEditMode = () => {
                // 输入框退出编辑模式
                rowData.editing = false;
                // 对比新旧值
                if (rowData[column.dataKey!] !== inputOriginValue) {
                    // 更新到服务器
                    if (checkPermi(['purchase:update'])) {
                        updatePurchase(rowData._id, column.dataKey!, rowData[column.dataKey!]).then(() => {
                            ElMessage.success('更新成功');
                        });
                    } else {
                        ElMessage.error('没有权限');
                    }
                }
            };

            return rowData.editing ? (
                <InputCell type={'textarea'} value={rowData[column.dataKey!]} onFocus={onEnterEditMode} onBlur={onExitEditMode} onInput={onInput} />
            ) : (
                <div
                    class={rowData[column.dataKey!] === '' ? 'table-v2-inline-editing-trigger-trim text' : 'table-v2-inline-editing-trigger text'}
                    onClick={onEnterEditMode}
                >
                    {rowData[column.dataKey!]}
                </div>
            );
        },
    },
    printFlag: {
        width: 50,
        key: 'printFlag',
        dataKey: 'printFlag',
        title: '打印',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <CheckBoxCell value={rowData[column.dataKey!]}></CheckBoxCell>;
        },
    },
    procurementControlInfo: {
        width: 200,
        key: 'procurementControlInfo',
        dataKey: 'procurementControlInfo',
        title: '单据信息',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            const onUpdateClick = () => {
                procurementControlInfoId.value = rowData['_id'];
                // 默认信息
                procurementControlInfo.arrivalQuantity = rowData[column.dataKey!][0].arrivalQuantity;
                procurementControlInfo.arrivalAmount = rowData[column.dataKey!][0].arrivalAmount;
                uploadprocurementControlInfoVisible.value = true;
            };

            const onClick = () => {
                procurementControlInfoId.value = rowData['_id'];
                procurementControlInfo.arrivalQuantity = 0;
                procurementControlInfo.arrivalAmount = 0;
                uploadprocurementControlInfoVisible.value = true;
            };

            return rowData[column.dataKey!].length > 0 ? (
                <div class={'flex items-center justify-between'}>
                    {rowData[column.dataKey!].map((item: any) => (
                        <div>
                            <div>到货量：{item.arrivalQuantity}</div>
                            <div>金额：{item.arrivalAmount}</div>
                            <div>单价：{Number(item.arrivalAmount / item.arrivalQuantity).toFixed(2)}</div>
                        </div>
                    ))}
                    <ElButton class={'ml-2'} type={'primary'} size={'small'} onClick={onUpdateClick}>
                        修改
                    </ElButton>
                </div>
            ) : (
                <ElButton type={'primary'} text size={'small'} onClick={onClick}>
                    上传
                </ElButton>
            );
        },
    },
    procurementControlReceipts: {
        width: 140,
        key: 'procurementControlReceipts',
        dataKey: 'procurementControlReceipts',
        title: '采购凭证',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 上传采购凭证
            const onUploadProcurementControlReceipts = () => {
                imageInfo.value.purchaseId = rowData['_id'];
                imageInfo.value.imageName = rowData['orderNo'] + '_' + rowData['productName'];
                uploadProcurementControlReceiptsVisible.value = true;
            };

            // 跳过采购凭证
            const skipProcurementControlReceipts = () => {
                skipProcurementControlReceiptsEvnet(rowData['_id']);
            };

            // 删除采购凭证
            const deleteProcurementControlReceipts = () => {
                deleteProcurementControlReceiptsEvent(rowData['_id']);
            };

            // 处理图片
            const previewSrcList = rowData.procurementControlReceipts.map((item: any) => (item !== '手动过检' ? httpUrl + item : item));

            if (rowData[column.dataKey!].length == 0) {
                return (
                    <div class={'flex w-full justify-between'}>
                        <ElButton size={'small'} onClick={skipProcurementControlReceipts}>
                            过检
                        </ElButton>
                        <ElButton size={'small'} onClick={onUploadProcurementControlReceipts}>
                            上传
                        </ElButton>
                    </div>
                );
            } else if (rowData[column.dataKey!][rowData[column.dataKey!].length - 1] == '手动过检') {
                return (
                    <div class={'flex w-full justify-between'}>
                        <ElText type={'warning'} tag={'b'}>
                            手动过检
                        </ElText>
                        <ElButton class={'sfc-el-button'} size={'small'} onClick={deleteProcurementControlReceipts}>
                            删除
                        </ElButton>
                    </div>
                );
            } else {
                return (
                    <div class={'flex w-full justify-between'}>
                        <div>
                            <ElButton class={'sfc-el-button'} size={'small'} onClick={onUploadProcurementControlReceipts}>
                                添加
                            </ElButton>
                            <ElButton class={'sfc-el-button'} size={'small'} onClick={deleteProcurementControlReceipts}>
                                删除
                            </ElButton>
                        </div>
                        <ElImage
                            src={previewSrcList[0]}
                            fit={'cover'}
                            previewSrcList={previewSrcList}
                            previewTeleported
                            hide-on-click-modal
                        ></ElImage>
                    </div>
                );
            }
        },
    },
    arrivalDate: {
        width: 170,
        key: 'arrivalDate',
        dataKey: 'arrivalDate',
        title: '到货日期',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 更新到货日期
            const onUpdate = (value: Date) => {
                if (checkPermi(['purchase:update'])) {
                    rowData[column.dataKey!] = value;
                    updatePurchase(rowData._id, column.dataKey!, value).then(() => {
                        ElMessage.success('更新成功');
                    });
                } else {
                    ElMessage.error('没有权限');
                }
            };

            return <DatePickerCell value={rowData[column.dataKey!]} onUpdate={onUpdate} />;
        },
    },
    orderDeliveryDate: {
        width: 170,
        key: 'orderDeliveryDate',
        dataKey: 'orderDeliveryDate',
        title: '订单交期',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            // 更新到货日期
            const onUpdate = (value: Date) => {
                if (checkPermi(['purchase:update'])) {
                    rowData[column.dataKey!] = value;
                    updatePurchase(rowData._id, column.dataKey!, value).then(() => {
                        ElMessage.success('更新成功');
                    });
                } else {
                    ElMessage.error('没有权限');
                }
            };
            return <DatePickerCell value={rowData[column.dataKey!]} onUpdate={onUpdate} />;
        },
    },
    creator: {
        width: 120,
        key: 'creator',
        dataKey: 'creator',
        title: '下单人',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{rowData[column.dataKey!]}</div>;
        },
    },
    createdAt: {
        width: 120,
        key: 'createdAt',
        dataKey: 'createdAt',
        title: '下单时间',
        align: 'center',
        cellRenderer: ({ rowData, column }) => {
            return <div class={'text'}>{formatTimeZone(rowData[column.dataKey!], 'YYYY-MM-DD')}</div>;
        },
    },
});

/* ******************************上传单据信息属性/方法****************************** */
// 上传单据信息窗显示
const uploadprocurementControlInfoVisible = ref(false);
// 需要上传的采购Id
const procurementControlInfoId = ref('');
// 需要上传的单据信息
const procurementControlInfo = reactive({
    arrivalQuantity: 0,
    arrivalAmount: 0,
});
// 上传单据信息事件
const uploadProcurementControlInfoEvent = () => {
    // 校验Id
    if (!procurementControlInfoId.value) {
        ElMessage.error('未知错误，请重新刷新网页后重试');
        return;
    }
    // 校验信息
    if (!procurementControlInfo.arrivalQuantity) {
        ElMessage.error('请输入到货数量');
        return;
    }
    if (!procurementControlInfo.arrivalAmount) {
        ElMessage.error('请输入到货金额');
        return;
    }
    // 权限校验
    if (checkPermi(['purchase:update'])) {
        uploadProcurementControlInfo(procurementControlInfoId.value, procurementControlInfo).then(() => {
            ElMessage.success('上传成功');
            uploadprocurementControlInfoVisible.value = false;
            getPurchaseListEvent();
        });
    } else {
        ElMessage.error('没有权限');
    }
};

/* ******************************上传采购凭证属性/方法****************************** */
// 上传采购凭证弹窗显示
const uploadProcurementControlReceiptsVisible = ref(false);
// 图片预览的src
const imageSrc = ref('');
// 图片的信息
const imageInfo = ref({
    purchaseId: '',
    imageName: '',
});
// 粘贴事件处理
const handlePaste = (event: ClipboardEvent) => {
    // 获取粘贴板数据
    const items = event.clipboardData?.items;
    // items 可能为空
    if (items) {
        // 遍历粘贴板数据
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            // 判断是否为图片
            if (item.type.indexOf('image') !== -1) {
                const blob = item.getAsFile();
                if (blob) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        imageSrc.value = e.target?.result as string;
                    };
                    reader.readAsDataURL(blob);
                }
            }
        }
    }
};
// 监听粘贴事件
const addEventListenerEvent = () => {
    window.addEventListener('paste', handlePaste);
};
// 移除监听粘贴事件
const removeEventListenerEvent = () => {
    imageSrc.value = '';
    window.removeEventListener('paste', handlePaste);
};
// 上传采购凭证事件
const uploadProcurementControlReceiptsEvent = async () => {
    if (imageSrc.value) {
        const formData = new FormData();
        const blob = await fetch(imageSrc.value).then((res) => res.blob());
        formData.append('file', blob, imageInfo.value.imageName.replace(/["'‘’“”.*+?^${}()|[\]\\]/g, '_') + '.png');
        formData.append('purchaseId', imageInfo.value.purchaseId);

        try {
            const response = await fetch(
                import.meta.env.VITE_APP_SERVER_URL + import.meta.env.VITE_APP_BASE_API + HttpUrl.uploadProcurementControlReceipts,
                {
                    method: 'POST',
                    body: formData,
                }
            );

            if (response.ok) {
                ElMessage.success('文件上传成功');
                // 重置状态
                imageSrc.value = '';
                uploadProcurementControlReceiptsVisible.value = false;
                getPurchaseListEvent();
            } else {
                ElMessage.error('文件上传失败');
            }
        } catch (error) {
            ElMessage.error('网络错误');
        }
    }
};
// 手动过检采购凭证
const skipProcurementControlReceiptsEvnet = async (purchaseId: string) => {
    skipProcurementControlReceipts(purchaseId).then(() => {
        ElMessage.success('过检成功');
        getPurchaseListEvent();
    });
};
// 删除采购凭证
const deleteProcurementControlReceiptsEvent = async (purchaseId: string) => {
    deleteProcurementControlReceipts(purchaseId).then(() => {
        ElMessage.success('删除成功');
        getPurchaseListEvent();
    });
};

/* ******************************操作栏属性/方法****************************** */
// 搜索采购值
const searchPurchaseValue = ref('');

// 进入回收站
const enterRecycleEvent = () => {
    available.value = false;
    page.value = 1;
    getPurchaseListEvent();
};

// 返回采购单
const returnPurchaseEvent = () => {
    available.value = true;
    page.value = 1;
    getPurchaseListEvent();
};

// 删除采购单
const deletePurchaseEvent = () => {
    if (selected.length == 0) {
        ElMessage.warning('请选择要删除的采购单');
        return;
    }
    // 删除采购单
    if (checkPermi(['purchase:delete'])) {
        ElMessageBox.confirm(`确定删除${selected.length}条采购单？`, '采购提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            deletePurchase(selected).then((res) => {
                ElMessage.success(res.message);
                getPurchaseListEvent();
            });
        });
    }
};

// 恢复采购单
const recoverPurchaseEvent = () => {
    if (selected.length == 0) {
        ElMessage.warning('请选择要恢复的采购单');
        return;
    }
    // 恢复采购单
    if (checkPermi(['purchase:delete'])) {
        ElMessageBox.confirm(`确定恢复${selected.length}条采购单？`, '采购提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }).then(() => {
            recoverPurchase(selected).then((res) => {
                ElMessage.success(res.message);
                getPurchaseListEvent();
            });
        });
    }
};

// 移除采购单
const removePurchaseEvent = () => {
    if (selected.length == 0) {
        ElMessage.warning('请选择要移除的采购单');
        return;
    }
    // 移除采购单
    if (checkPermi(['purchase:delete'])) {
        ElMessageBox.confirm(`确定移除${selected.length}条采购单？`, '采购提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }).then(() => {
            removePurchase(selected).then((res) => {
                ElMessage.success(res.message);
                getPurchaseListEvent();
            });
        });
    }
};

// 转移采购到库存纸
const transferStockEvent = () => {
    if (selected.length !== 1) {
        ElMessage.warning('请选择一条要转移的采购单');
        return;
    }

    transferStock(selected[0]).then((res) => {
        selected.length = 0;
        ElMessage.success(res.message);
        getPurchaseListEvent();
    });
};

/* ******************************标签属性/方法****************************** */
// 打印采购标签dialog
const printPurchaseLabelVisible = ref(false);

// 采购标签内容
const printPurchaseLabelData = reactive<{
    supplierAbbreviation: string;
    customerAbbreviation: string;
    size: string;
    productName: string;
    purchaseNumber: number;
    orderDeliveryDate: Date | string;
    orderNo: string;
    notes: string;
}>({
    supplierAbbreviation: '',
    customerAbbreviation: '',
    size: '',
    productName: '',
    purchaseNumber: 0,
    orderDeliveryDate: '',
    orderNo: '',
    notes: '',
});

// 打印采购标签事件
const printLabelEvent = () => {
    if (selected.length !== 1) {
        ElMessage({
            message: '请先选中一个采购后，再进行打印。',
            type: 'warning',
            grouping: true,
        });
    } else {
        // 清空上次数据
        printPurchaseLabelData.supplierAbbreviation = '';
        printPurchaseLabelData.customerAbbreviation = '';
        printPurchaseLabelData.size = '';
        printPurchaseLabelData.productName = '';
        printPurchaseLabelData.purchaseNumber = 0;
        printPurchaseLabelData.orderDeliveryDate = '';
        printPurchaseLabelData.orderNo = '';
        printPurchaseLabelData.notes = '';
        // 加载数据
        const singleOrder = data.find((item) => item._id == selected[0]);
        printPurchaseLabelData.supplierAbbreviation = singleOrder?.supplierAbbreviation || '';
        printPurchaseLabelData.customerAbbreviation = singleOrder?.customerAbbreviation || '';
        printPurchaseLabelData.size = singleOrder?.tissueSize == '' ? singleOrder?.corrugatedSize : singleOrder?.tissueSize || '';
        printPurchaseLabelData.productName = singleOrder?.productName || '';
        printPurchaseLabelData.purchaseNumber = singleOrder?.purchaseNumber || 0;
        printPurchaseLabelData.orderDeliveryDate = singleOrder?.orderDeliveryDate || '';
        printPurchaseLabelData.orderNo = singleOrder?.orderNo || '';
        // 打开打印的dialog
        printPurchaseLabelVisible.value = true;
    }
};

/* ******************************生产单属性/方法****************************** */
// 打印生产单的dialog可见性
const printVisible = ref(false);
// 打印数据
const printData = reactive<
    { orderId: string; customerId: string; productId: string; orderNumber: number; purchaseNumber: number; orderDeliveryDate: Date | string }[]
>([]);
// 打印生产单
const printProductionEvent = () => {
    if (selected.length <= 0) {
        ElMessage({
            message: '请先选中一个或多个产品后，再进行打印。',
            type: 'warning',
            grouping: true,
        });
    } else {
        // 清空上次数据
        printData.splice(0);
        // 加载数据
        for (let index = 0; index < selected.length; index++) {
            const select = selected[index];
            const singleOrder = data.find((item) => item._id == select);
            printData.push({
                orderId: select,
                customerId: singleOrder?.customerId || '',
                productId: singleOrder?.productId || '',
                orderNumber: singleOrder?.orderNumber || 0,
                purchaseNumber: singleOrder?.purchaseNumber || 0,
                orderDeliveryDate: singleOrder?.orderDeliveryDate || '暂无送货计划',
            });
        }
        // 去空
        for (let index = 0; index < printData.length; index++) {
            const data = printData[index];
            if (data.customerId == '' || data.productId == '') {
                printData.splice(index, 1);
                index--;
            }
        }
        // 打开打印的dialog
        printVisible.value = true;
    }
};
// 关闭打印生产单dialog，则更新采购单列表
watch(
    () => printVisible.value,
    (newValue) => {
        // 关闭打印生产单dialog，则更新
        if (!newValue) {
            getPurchaseListEvent();
        }
    }
);

/* ******************************展示栏属性/方法****************************** */
// 勾选框勾选的值 usePurchase.able

// 勾选框数据（able+disable）
const checkBoxOptions = reactive([
    { disabled: false, label: '序号', value: 'order' },
    { disabled: false, label: '客户', value: 'customerAbbreviation' },
    { disabled: false, label: '订单状态', value: 'orderStatus' },
    { disabled: false, label: '订单号', value: 'orderNo' },
    { disabled: false, label: '产品名称', value: 'productName' },
    { disabled: false, label: '产品尺寸', value: 'productSize' },
    { disabled: false, label: '供应商', value: 'supplierAbbreviation' },
    { disabled: false, label: '面纸规格', value: 'tissueSize' },
    { disabled: false, label: '瓦楞规格', value: 'corrugatedSize' },
    { disabled: false, label: '材质', value: 'materialQuality' },
    { disabled: false, label: '压线', value: 'crimping' },
    { disabled: false, label: '拼数', value: 'spell' },
    { disabled: false, label: '订单数量', value: 'orderNumber' },
    { disabled: true, label: '采购数量', value: 'purchaseNumber' },
    { disabled: true, label: '送货地址', value: 'arrivalTo' },
    { disabled: false, label: '订单备注', value: 'orderRemark' },
    { disabled: false, label: '采购备注', value: 'purchaseNotes' },
    { disabled: true, label: '打印标识', value: 'printFlag' },
    { disabled: false, label: '单据信息', value: 'procurementControlInfo' },
    { disabled: false, label: '采购凭证', value: 'procurementControlReceipts' },
    { disabled: false, label: '到货日期', value: 'arrivalDate' },
    { disabled: false, label: '交货日期', value: 'orderDeliveryDate' },
    { disabled: false, label: '下单人', value: 'creator' },
    { disabled: false, label: '下单时间', value: 'createdAt' },
]);
// 列举所有可用列（able+disable）
const allColumn = [
    'order',
    'customerAbbreviation',
    'orderStatus',
    'orderNo',
    'productName',
    'productSize',
    'supplierAbbreviation',
    'tissueSize',
    'corrugatedSize',
    'materialQuality',
    'crimping',
    'spell',
    'orderNumber',
    'purchaseNumber',
    'arrivalTo',
    'orderRemark',
    'purchaseNotes',
    'printFlag',
    'procurementControlInfo',
    'procurementControlReceipts',
    'arrivalDate',
    'orderDeliveryDate',
    'creator',
    'createdAt',
];
// 监听复选框变化
const checkBoxChangeEvent = (val: CheckboxValueType[]) => {
    // 反向输入禁用列 -- able有的disable就不能有
    const _disable = allColumn.filter((item) => !val.includes(item));
    // 先清空禁用
    usePurchase.disable.length = 0;
    _disable.forEach((item) => {
        usePurchase.disable.push(item);
    });
    // 禁用available，永不开启
    usePurchase.disable.push('available');
};

/* ******************************分页属性/方法****************************** */
// 处理分页大小变化
const handleSizeChange = () => {
    if (pageSizeSymbol.value) {
        getPurchaseListEvent();
    }
};
</script>

<style>
.purchase-container {
    height: calc(100vh - 80px);
    overflow: hidden;
    .purchase-nav {
        height: 100px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
    }
    .purchase-table {
        height: calc(100vh - 220px);
        width: 100%;
    }
    .purchase-pagination {
        height: 40px;
        display: flex;
        align-items: center;
    }
}
.text {
    word-break: break-all; /* 或者使用 word-break: break-word; */
    overflow-wrap: break-word; /* 兼容旧浏览器使用 word-wrap: break-word; */
}
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
.sfc-el-button + .sfc-el-button {
    margin-left: 0px !important;
}
</style>
